<?php
use EasyWeChat\Factory;
require_once("./vendor/autoload.php");
require_once("./lib/fun.php");
require_once("./lib/pdo.php");
// $user_data = file_get_contents('./login.txt');
$param = I('param.');
$rule  = [
    'code'  => [
        'type'         => 'string',
        'is_necessary' => 1,
        'name' => 'code',
    ],
    'iv'  => [
        'type'         => 'string',
        'is_necessary' => 1,
        'name' => 'iv',
    ],
    'encryptedData'  => [
        'type'         => 'string',
        'is_necessary' => 1,
        'max' => 500,
        'name' => 'encryptedData',
    ],
];
$check = CheckParams($param,$rule);
if(!$check['success']){
    $msg = explode(";",$check['msg']);
    json([
        'code' => 0,
        'msg'  => $msg[0] ?? "",
    ]);
}
$mini_config = [
        'app_id' => 'wxfd7508b055adc597',
        'secret' => '4ab33c908b3b8461f4c575d21d9b4a37',
        // 下面为可选项
        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',
        'log' => [
            'level' => 'debug',
            'file' => 'wechat.log',
        ],
    ];
$app = Factory::miniProgram($mini_config);
$session_data = $app->auth->session($param['code']);

 if(empty($session_data['openid'])){
    json([
        'code' => 0,
        'msg'  => '登录失败',
    ]);
}

$model = db("lu_user");
$share_set_model = db('lu_share_set');
$share_set_info = $share_set_model->where(['id' => 1])->find();
//用户信息
$user_vip = db('lu_share_user_vip');
$vip_model = db('lu_vip');

$decryptedData = $app->encryptor->decryptData($session_data['session_key'], $param['iv'], $param['encryptedData']);

$where = [
    "openid" => $session_data['openid'],
];

$info = $model->where($where)->find();
$is_add = 0;
$psd = "";
if($info){
    if($decryptedData["phoneNumber"]){
        $model->where($where)->update([
            'mobile' => $decryptedData["phoneNumber"]
            ]);
    }
   json([
        'code' => 1,
        'msg'  => '登录成功',
        'token' => authcode($info['id'],'ENCODE',"youluda",30*24*3600),
    ]);
}else{
    $psd = createCode();
    if($decryptedData["phoneNumber"]){
          $where = [
            "mobile" => $decryptedData['phoneNumber'],
        ];
        $user_info = $model->where($where)->find();
        if($user_info){
            //关联小程序
            $model->where(['id' => $user_info['id']])->update([
                "openid" => $session_data['openid'],
            ]);
            json([
                'code' => 1,
                'msg'  => '登录成功',
                'token' => authcode($user_info['id'],'ENCODE',"youluda",30*24*3600),
            ]);
        }
    }
    //判断是否存在
    $add = [
        'openid' => $session_data['openid'],
        'mobile' => $decryptedData["phoneNumber"] ?? "",
        'add_time' => date("Y-m-d H:i:s"),
        'share_id' => $param['share_id'] ?? 0,
        'psd' => md5($psd."_youluda"),
        ];
    $id = $model->add($add);
    $is_add = 1;
    
    //分享数据
    if(!empty($param['share_id'])){
        $vip_info = $vip_model->where("id",$share_set_info['vip_id'])->find();
        if($vip_info){
            $where_vip = [
                'uid' => $param['share_id'],
            ];
            $total_num = $user_vip->where($where_vip)->count();
            
            $where_share = [
                'share_id' => $param['share_id'],
            ];
            $share_num = $model->where($where_share)->count();
            
            $add_vip = 0;
            if($share_set_info['is_multi']){
                $add_vip = $share_num >= ($share_set_info['num'] * ($total_num + 1)) ? 1 : 0;
            }else{
                $add_vip = $total_num ? 0 : 1;
            }
            if($add_vip){
                if($share_set_info['day_num']){
                    $vip_time = $share_set_info['day_num']  * 24 * 3600;
                }else{
                    $vip_time = $vip_info['month'] * 30 * 24 * 3600;
                }
                
                $share_user_info = $model->where(["id" => $param['share_id']])->find();
                
                if($share_user_info['vip_time'] < time()){
                    $update = [
                        'vip_time' => time() + $vip_time,
                        'vip_id' => $vip_info['id'],
                        'limit_plan_num' => $share_set_info['plan_num'] ? $share_set_info['plan_num'] : $vip_info['plan_num'],
                        'limit_address_num' => $share_set_info['address_num'] ? $share_set_info['address_num'] : $vip_info['address_num'],
                        'type' => $vip_info['type'] ?? 0,
                        
                        ];
                    $res = $model->where(["id" => $param['share_id']])->update($update);
                }else{
                    $update = [
                        'vip_time' => $share_user_info['vip_time'] + $vip_time,
                        'vip_id' => $vip_info['id'],
                        'limit_plan_num' => $share_set_info['plan_num'] ? $share_set_info['plan_num'] : $vip_info['plan_num'],
                        'limit_address_num' => $share_set_info['address_num'] ? $share_set_info['address_num'] : $vip_info['address_num'],
                        'type' => $vip_info['type'] ?? 0,
    
                        ];
                    $res = $model->where(["id" => $param['share_id']])->update($update);
                }
                $add_share  = [
                    'vip_id' => $vip_info['id'],
                    'uid' => $param['share_id'],
                    'add_time' => date("Y-m-d H:i:s"),
                    ];
                $user_vip->add($add_share);
            
            }
            
        }
        
    }
    $msg = "登录成功";
    if($psd){
        $msg .= ",您的初始化密码是:".$psd;
    }
    json([
        'code' => 1,
        'msg'  => $msg,
        'token' => authcode($id,'ENCODE',"youluda",30*24*3600),
    ]);
}

function createCode($length = 6){
    $key = "";
    $num = "123456789";
    for($i=0;$i<$length;$i++){
        $key .= $num[mt_rand(0,8)];
    }
    return $key;
}

?>